package com.daylightrobbery.server.handler;

import com.daylightrobbery.server.packet.GamePacket;
import org.apache.juli.logging.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.security.util.Debug;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

public class PlayerPacketManager {

    private static final Logger log = LoggerFactory.getLogger(PlayerPacketManager.class);

    private static final int BUFFER_LENGTH = 1 << 16; // 总大小

    private AtomicLong packetIdGenerator;
    public GamePacket[] packets;
    private long left; // 窗口起始位置

    public PlayerPacketManager(long startId){
        packets = new GamePacket[BUFFER_LENGTH];
        left = startId;
        packetIdGenerator = new AtomicLong(left);
    }


    public long generateId(){
        return packetIdGenerator.getAndIncrement();
    }

    public List<GamePacket> processGamePacket(GamePacket p) {
        List<GamePacket> result = new LinkedList<>();
        String uid = p.getUid();
        Long id = p.getId();
        log.info("[" + uid + "] 期望packetId: " + left + " 收到id: " + p.getId() + " ");
        if(id < left){
            log.info("丢弃重复处理的数据包: " + p.getId());
            return result;
        }
        if(left == id) {
            // 从左往右找
            int bufferIndex = (int) (left & (BUFFER_LENGTH - 1));
            packets[bufferIndex] = p;
            for (int i = bufferIndex; i < BUFFER_LENGTH; i = i == BUFFER_LENGTH - 1 ? 0 : i + 1) {
                GamePacket packet = packets[i];
                if (packet != null) {
                    result.add(packet);
                    left++;
                    packets[i] = null;
                }else{
                    // 为空了，跳出数组
                    break;
                }
            }
        }else{
            log.info("等待 数据包[" + left +"]...");
            int bufferIndex = (int) (id & (BUFFER_LENGTH - 1));
            packets[bufferIndex] = p;
        }
        return result;

    }
}
